package com.ldf.jrtsp.handler;

import com.ldf.jrtsp.parser.RtspDataParser;
import com.ldf.jrtsp.player.RtspPlayer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ldf.jrtsp.constants.RtspConstants.RTSP_OK;
import static com.ldf.jrtsp.enums.RtspOptionsType.SETUP;
import static com.ldf.jrtsp.enums.RtspOptionsType.TEARDOWN;

/**
 * setup reply handle
 *
 * @author lidaofu
 * @since 2024/6/19
 **/
public class RtspSetupReplyHandle implements RtspReplyHandle {
    private final static Logger log = LoggerFactory.getLogger(RtspSetupReplyHandle.class);
    private final static Pattern serverPortPattern = Pattern.compile("server_port=(\\d+)-(\\d+)");
    private final static Pattern clientPortPattern = Pattern.compile("client_port=(\\d+)-(\\d+)");
    private final static Pattern ssrcPattern = Pattern.compile("ssrc=(.*?);");

    @Override
    public void handle(RtspPlayer player, RtspDataParser rtspDataParser) {
        if (rtspDataParser.getResponse().equals(RTSP_OK)) {
            String session = rtspDataParser.getHeaders().get("Session");
            String[] sessionAndTimeout = session.split(";");
            player.setSession(sessionAndTimeout[0].trim());
            if (sessionAndTimeout.length > 1) {
                player.setTimeout(Integer.parseInt(sessionAndTimeout[1].split("=")[1]));
            }else {
                player.setTimeout(60);
            }
            player.createRtspKeepAliveTask();
            String transport = rtspDataParser.getHeaders().get("Transport");
            Matcher serverPortMatcher = serverPortPattern.matcher(transport);
            Matcher clientPortMatcher = clientPortPattern.matcher(transport);
            if (serverPortMatcher.find() && clientPortMatcher.find()) {
                int serverPort = Integer.parseInt(serverPortMatcher.group(1).split("-")[0]);
                int clientPort = Integer.parseInt(clientPortMatcher.group(1).split("-")[0]);
                player.setRemoteRtpPort(serverPort, clientPort);
            }
            Matcher ssrcMatcher = ssrcPattern.matcher(transport);
            if (ssrcMatcher.find()) {
                player.setSsrc(ssrcMatcher.group(1));
            }
        } else {
            log.warn("rtsp setup reply is {}", rtspDataParser.getResponse());
        }
        player.sendOptionsCallBack(SETUP,rtspDataParser);
    }

}
